<!--  -->
<template>
    <el-dialog v-model="dialogVisible" :title="ruleForm.id > 0 ? '修改职员' : '添加职员'" width="700" :before-close="handleClose">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="elform" label-width="auto">
   
        <el-form-item class="photo" label="头像">
          <el-upload :headers="headers" class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="ruleForm.photo" :src="imgBaseUrl + ruleForm.photo" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
  
        </el-form-item>
  
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
  
        <el-form-item label="管辖范围">
          <Buildings v-model="buildingIds" :multiple="true" :checkStrictly="false"></Buildings>
        </el-form-item>
  
        <el-form-item prop="type" label="职员类型">
          <el-select v-model="ruleForm.type" placeholder="请选择职员类型">
            <el-option v-for="item in types" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
  
        <el-form-item label="性别">
          <el-radio-group v-model="ruleForm.sex">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
  
  
        <el-form-item label="证件">
          <el-input v-model="ruleForm.cardid" />
        </el-form-item>
  
        <el-form-item label="电话">
          <el-input v-model="ruleForm.mobile" />
        </el-form-item>
  
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">Cancel</el-button>
          <el-button type="primary" @click="submit">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </template>
  <script lang="ts" setup>
  import Buildings from '../building/Buildings.vue';
  import { onMounted, reactive, watch } from 'vue'
  import { Staff } from '../../service/staffs/type';
  import { TypeList,add } from "../../service/staffs/staffs"
  import { ref, defineEmits, defineProps } from 'vue'
  import {  ElMessage, FormRules, FormInstance } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import { useUserStore } from '../../store/index';
  const store = useUserStore();
  
  
  const uploadUrl = import.meta.env.VITE_BASE_URL + "upload/add";
  const imgBaseUrl = ref(import.meta.env.VITE_IMG_URL);
  const headers = { Authorization: store.token }
  const ruleFormRef = ref<FormInstance>()
  //表单数据
  const ruleForm = ref<Staff>({
    id: 0,
    name: "",
    photo: "",
    type: null,
    sex: null,
    mobile: "",
    cardid: "",
    pass: "",
    state: 0,
    building: []
  })
  const pros= defineProps({
    editData:{
      type:Object
    }
  })
  
  //楼栋选择
  const buildingIds=ref<any>();
  
  watch(buildingIds,(newValue)=>{
  
    ruleForm.value.building=  newValue.map((item:any)=>{
      
       if(typeof item=="object"){
         return {buildingid:item[item.length-1]};
       }
       else{
        return {buildingid:item};
       }
    });
  })
  const rules = reactive<FormRules<Staff>>({
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择类型', trigger: 'blur' }
    ]
  
  })
  
  //图片上传
  import type { UploadProps } from 'element-plus'
//   import { storeToRefs } from 'pinia';
  
  // const imageUrl = ref('')
  
  const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,

    // uploadFile
  ) => {
  
    if (response.errCode === 10000) {
  
      ruleForm.value.photo = response.data;
    }
  }
  
  const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('只能上传JPG|PNG格式文件!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('上传的图片不能超过2MB!')
      return false
    }
    return true
  }
  
  
  
  const dialogVisible = ref(true)
  
  //职员类型
  const types = ref<any>([]);
  const getTypeData = async () => {
    const res: any = await TypeList();
    if (res.errCode === 10000) {
      types.value = res.data.list;
    }
  }
  
  const emit = defineEmits(["close"]);
  const handleClose = () => {
    emit("close");
  }
  //提交
  const postData = async () => {
  
    const res:any=await add(ruleForm.value);
    console.log(1111,res);
    if(res.errCode===10000){
      emit("close",true);
    }
    
  
  }
  
  const submit = async () => {
  
    await ruleFormRef.value!.validate((valid) => {
      if (valid) {
        postData();
      }
    })
  
  }
  onMounted(() => {
    getTypeData();
  //深拷贝
    //  ruleForm.value=JSON.parse(JSON.stringify(pros.editData as Staff));
     ruleForm.value={...pros.editData} as Staff
  
      
     buildingIds.value=ruleForm.value.building?.length?  ruleForm.value.building.map((item:any)=>item.buildingid) : [];
     
  // Object.assign( ruleForm.value,pros.editData)
  
  })
  </script>
  
  <style scoped lang="less">
  .elform {
    padding: 30px 50px;
    display: block;
  
  }
  
  .el-form-item {
    width: 500px;
  
  
  }
  
  .photo {
  
    height: 80px;
    display: flex;
    align-items: center;
  
  }
  
  /deep/ .avatar-uploader .el-upload {
    width: 80px;
    height: 80px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  .elform {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.form-container {
  display: flex;
  justify-content: space-between;
}

.form-column {
  flex: 1;
  min-width: 300px;
}
  .avatar {
    width: 100%;
    height: 100%;
  }
  </style>